package com.zhentao.login.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import com.zhentao.login.constants.Constants;
import com.zhentao.login.redis.RedisCacheUtil;
import com.zhentao.nlz.project.login.TUser;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Configuration
public class JwtToken {
    private static String str="zt666";
    @Resource
    RedisCacheUtil redisCacheUtil;
    /**
     * 创建jwt
     * @return
     */
    public String createJetToken(TUser tUser){
        //创建token  会将用户数据存放到redis中，方便实现单点登录，踢人下线，查看在线用户等功能
        //String tokenKey = UUID.randomUUID().toString().replaceAll("-", "");

        Map<String,Object> claims=new HashMap<>();
        claims.put("tokenKey",tUser.getUserId());

        //会将数据存储到redis  key:token value:loginUserVo
        //redisCacheUtil.setCacheObject(Constants.LOGIN_USER_KEY +tUser.getId(),tUser,1, TimeUnit.HOURS);
        String token = JWT.create()
                //添加载荷
                .withClaim("claims", claims)
                //添加过期时间
                //.withExpiresAt(getCalendar().getTime())
                //指定算法 配置密码
                .sign(Algorithm.HMAC256(str));
        return token;
    }

    /**
     * 获取过期时间 System.currentTimeMillis(); 可能出现负数
     * @return
     */
    public Calendar getCalendar() {
        Calendar c=Calendar.getInstance();
        c.set(Calendar.SECOND, 60*60*12);
        return c;
    }

   /* public Map<String,Object> resolveJwt(String headerToken){
        //require申请一个JWT的验证器 通过build生成一个验证器
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(str)).build();
        //通过 verifier 去验证token 生成解析后的jwt对象
        DecodedJWT verify = verifier.verify(headerToken);
        Map<String, Object> claims = verify.getClaim("claims").asMap();
        return claims;

    }*/

    public Object getLoginUser(String token) {
        if(ObjectUtil.isNotEmpty(token)) {
            //require申请一个JWT的验证器 通过build生成一个验证器
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(str)).build();
            //通过 verifier 去验证token 生成解析后的jwt对象
            DecodedJWT verify  = verifier.verify(token);
            Map<String, Object> claims = verify.getClaim("claims").asMap();
            Integer userId = (Integer) claims.get("tokenKey");
            TUser tUser = redisCacheUtil.getCacheObject(Constants.LOGIN_USER_KEY + userId);
            if(BeanUtil.isEmpty(tUser)){
                return null;
            }
            return tUser;
        }
        return null;
    }

    public void refreshToken(TUser tUser,Integer time,TimeUnit unit){
            redisCacheUtil.setCacheObject(Constants.LOGIN_USER_KEY + tUser.getUserId(), tUser, time, unit);
    }
    public void removeToken(TUser tUser){
            redisCacheUtil.deleteObject(Constants.LOGIN_USER_KEY +tUser.getUserId());
    }
}
